
<template>
  <massif-layout :leftWidth="showLeftView?'300px':'0'" :showBack="true" @back="goBack">
      <template v-slot:left>
          <!--显示选择地块列表-->
          <div class="select-land-left-view" v-if="showLeftView">
              <div class="mass-view">
                  <div class="name">已选地块<span style="color: #00b070;font-size:15px;">({{selectLandList.length}})</span></div>
                  <div style="color: #00b070;font-size:14px;">{{getMapSize}}(亩)</div>
              </div>
              <div>
                  <div> 
                      <el-input placeholder="搜索地块名称" clearable v-model="sreachText" >
                          <template #append>
                              <vxe-icon name="search" size="mini"></vxe-icon>
                          </template> 
                      </el-input>
                  </div>
                  <div class="filter-view" >
                      <el-select v-model="selectText" v-if="showFooter" style="width:120px;" clearable placeholder="全部">
                          <el-option v-for="item in groupList" :label="item.groupName" :value="item.landGroupId"></el-option>
                      </el-select>
                       <vxe-button mode="text" v-if="showFooter" @click="btnAllDel"  icon="vxe-icon-delete" size="small" status="danger" content="清空"></vxe-button>
                  </div>
                <!--地块列表显示容器-->
                  <landList :tableData="getLandTable" :showDel="showFooter" @onClick="setMapData" @onDelete="delCell" />
              </div>
          </div>
      </template>
      <div class="right-view-map">
        <div class="tips-view-tools" v-if="showFooter">
          <vxe-input v-model="searchInfo.farmLandName" 
              @blur="changeFarmLandName" 
              @clear="changeFarmLandName"
              placeholder="请输入地块名称" 
              type="search" 
              clearable></vxe-input>
              <querySelect  @change="changeLandType" />
              <vxe-button  size="small" 
              style="height:34px;width:50px;"
               @click="btnOpen"
               title="展开/隐藏"
               :icon="showLeftView?'vxe-icon-arrow-double-left':'vxe-icon-arrow-double-right'"></vxe-button>
        </div>
         <vxe-button 
          size="small" 
         @click="btnBack" 
         style="position: absolute;top:10px;right:10px;z-index:999;" 
         icon="vxe-icon-arrow-left">返回</vxe-button>
          <!--地图容器-->
          <MapViewer ref="refLandMap" 
              searchLeft="320px"
              domId="select-land-map"
              @onInit="initMap"
              :location="locationMap"
              @onDrag="changePostion"
              @onDragEnd="changePostion"
              @onZoom="changePostion"
              @onZoomEnd="onChangeZoom"
              :searchPanel="false" />
          <PoiPopup v-if="showPop"  :popOption="popObjct"    @onClose="showPop=false" />
          <div class="groug-change-view" v-if="showFooter">
            <div class="groug-list">
                <div class="item on">已选地块</div>
                <div class="item">未选地块</div>
                <!-- <div class="item not" v-if="showFooter">占用地块</div> -->
            </div>
          </div>
          <div class="groug-right-view" v-if="showFooter">
            <div>提示：点击选择或切换分组来选择地块</div>
            <div class="choose-land">
                <el-checkbox v-model="checkedLand" @change="changeCheckBox"></el-checkbox> 全选地块
            </div>
            <vxe-button
            status="primary"
            size="small"
            @click="saveLand"
            :content="`确定 (${selectLandList.length})`" icon="vxe-icon-check"></vxe-button>
          </div>
      </div>
  </massif-layout>
</template>

<script setup>
import {computed, onMounted, reactive, ref, watch} from 'vue'
import {getLandGroupList, getLandTypeList} from '@/api/plant'
import massifLayout from '../components/layout.vue'
import {useUserStore} from '@/pinia/modules/user'
import landList from './components/landList.vue'
import querySelect from './components/querySelect.vue'
import MapViewer from "@/components/gisMapBox/index.vue";
import PoiPopup from '@/components/gisMapBox/components/PoiPopup.vue';
import {getPageList} from '@/utils/common'
import {getLandMiniList} from '@/api/gis'

const emit = defineEmits(['close','change','complete','onInitMap'])
const userStore = useUserStore()
const tableData = ref([])
const fristTableData = ref([])
const selectLandList = ref([])
const showLeftView = ref(false)
const checkedLand = ref(false)
const showPop = ref(false)
const sreachText = ref('')
const selectText = ref('')
const groupList = ref('')
const landTypeList = ref([])
const popObjct = ref({})
const landInfo = ref({})
const searchInfo = ref({
    farmLandName:'',
    landGroupId:'',
    landTypeId:'',
    landTagId:''})
let refLandMap =ref(null)
let mapView = null
const props = defineProps({
  dataList: {
  type: Array,
  default: []
},
selectList: {
  type: Array,
  default: []
},
landDataList:{
  type: Array,
  default: []
},
openCount:{
  type: Number,
  default: 1
},
showFooter:{
  type: Boolean,
  default: true
},
plantingPlanId:{
  type:String,
  default:null
},
edit:{
  type:Boolean,
  default:false
}
})

watch(()=>props.selectList,(n,o)=>{
  if(props.selectList.length>0){
    selectLandList.value =props.selectList
   
    let centerList  =[]
    if(!props.showFooter){
      tableData.value= fristTableData.value.filter((item)=>selectLandList.value.includes(item.farmLandId))
      tableData.value.forEach((item)=>{
        centerList.push([Number(item.locationLongitude),Number(item.locationLatitude)])
      })
      refLandMap.value.locationCenter(centerList)
      updateData()
    }else{
       selectLandList.value.forEach((farmLandId)=>{
        mapView.setFeatureState({source: 'polygons-source', id: farmLandId },{ click: true });
      })
     let centerTable= fristTableData.value.filter((item)=>selectLandList.value.includes(item.farmLandId))
      centerTable.forEach((item)=>{
        centerList.push([Number(item.locationLongitude),Number(item.locationLatitude)])
      })
      refLandMap.value.locationCenter(centerList)
    }
  }else{
    selectLandList.value =[]
    checkedLand.value=false
  }
})


const locationMap = ref({})
//获取地块表
const getLandTable = computed(()=>{
  let list= fristTableData.value.filter((item) => {
    return selectLandList.value.includes(item.farmLandId)
  })
  if(sreachText.value){
    list = list.filter((item) => {
    return item.farmLandName.indexOf(sreachText.value)>=0
  })
  }
   return list
})

onMounted(()=>{
  getSelectList()
})

const initMap =async (view)=>{
  mapView = view
  emit('onInitMap',view)
     //编辑地块条件
     let params ={}
    if(props.edit && props.plantingPlanId){
          params ={
            farmId:userStore.userInfo.farmId, 
            companyId:userStore.userInfo.companyId,
            plantingPlanId:props.plantingPlanId,
            purPlantingPlanId:props.plantingPlanId,
            farmLandStatus:1
          }
         let  params2 ={
            farmId:userStore.userInfo.farmId, 
            companyId:userStore.userInfo.companyId,
            farmLandStatus:0
          }
          //编辑的时候查找未使用地块
         window.setTimeout(async () => {
            getMapList(params2,2)
          }, 2000);
    }else if(!props.edit && props.plantingPlanId){ 
        params ={
            farmId:userStore.userInfo.farmId, 
            companyId:userStore.userInfo.companyId,
            plantingPlanId:props.plantingPlanId,
            purPlantingPlanId:props.plantingPlanId
          }
    }else{
        params ={
            farmId:userStore.userInfo.farmId, 
            companyId:userStore.userInfo.companyId,
            farmLandStatus:0
          }
     }
     getMapList(params,1)
}

const getMapList = (params,type)=>{
  let pages =getPageList(6000)
        pages.forEach(async (item)=>{
            window.setTimeout(async () => {
                let res =await getLandMiniList({...params,...item})
                if(res?.success &&res.data?.length>0){
                  tableData.value =tableData.value.concat(res.data.filter((item)=>item.geom!=null))
                    if(item.page==1 && type==1){
                        addLandList()
                    }else{
                       updateData()
                  }
                  emit('complete',tableData.value)
                  fristTableData.value = tableData.value
                }
            }, item.page==1?0:(item.page*200));
        })
}

const updateData =()=>{
    let filterList =tableData.value.filter((item)=>{
     return (item.landGroupId == searchInfo.value?.landGroupId ||!searchInfo.value?.landGroupId) &&
          (item.landTypeId == searchInfo.value?.landTypeId ||!searchInfo.value?.landTypeId) &&
          (item.tagsId?.indexOf(searchInfo.value?.landTagId)>=0||!searchInfo.value?.landTagId) &&
          (item.cropId == searchInfo.value?.cropId ||!searchInfo.value?.cropId) &&
          (item.farmLandName?.indexOf(searchInfo.value?.farmLandName)>=0||!searchInfo.value.farmLandName)
           }).map((item)=> {
                  if(item?.geom && item.geom!='null' && item.geom !=null){
                    return {
                        type: 'Feature',
                        id:item.farmLandId,
                        properties: {
                            description: item.farmLandName+'\n'+Number(item.mapAreaSize||0).toFixed(2)+'亩',
                            lineColor:'#25c289',
                            lineWidth:3,
                            ...item
                        },
                        geometry: {
                            type: 'Polygon',
                            coordinates: [JSON.parse(item.geom||'[]')]
                        }
                    }
            }
    })
    mapView?.getSource('polygons-source')?.setData({type: 'FeatureCollection', features:filterList})
    let centerList =[]
    filterList.forEach((item)=>{
            centerList.push([Number(item.properties.locationLongitude),Number(item.properties.locationLatitude)])
        })
    refLandMap.value.locationCenter(centerList)
}

const addSourceData =()=>{
         mapView.addSource('polygons-source', {
            type: 'geojson',
            data: {
                type: 'FeatureCollection',
                features: tableData.value.map((item)=> {
                  if(item?.geom && item.geom!='null' && item.geom !=null){
                    return {
                        type: 'Feature',
                        id:item.farmLandId,
                        properties: {
                            description: item.farmLandName+'\n'+Number(item.mapAreaSize||0).toFixed(2)+'亩',
                            lineColor:'#25c289',
                            lineWidth:3,
                            ...item
                        },
                        geometry: {
                            type: 'Polygon',
                            coordinates: [JSON.parse(item.geom||'[]')]
                        }
                    }
                  }
                })
            }
    })
}

const addLandList =()=>{
       addSourceData()
       //添加线条
       mapView.addLayer({
            'id': 'polygons-layer-line',
            'type': 'line',
            'source': 'polygons-source',
            'layout': {},
            'paint': {
                'line-color': ['get', 'lineColor'],
                'line-width': ['get', 'lineWidth']
            }
    })

    // 添加多边形图层-图层
    mapView.addLayer({
            'id': 'polygons-layer-fill',
            'type': 'fill',
            'source': 'polygons-source',
            'paint': {
            'fill-opacity': 1,
              'fill-color': [
                'case',
                ['boolean', ['feature-state', 'click'], false],
                '#25c289',
                'rgba(255, 255, 255, 0)']
              },
              "interactive": true
        })

        // 添加多边形图层-文字
        mapView.addLayer({
            'id': 'polygons-layer-text',
            'type': 'symbol',
            'source': 'polygons-source',
            layout: {
                'text-field': ['get', 'description'],
                'text-size': 12,
                'text-anchor': 'center',
                'visibility': 'none',
                'text-offset': [0, 1.5],
                "text-translate": [0, 1],
                "text-translate-anchor": "map",
                'text-offset': [0, 1.5],
            },
            paint: {
              'text-color': '#ffffff',
                "text-halo-color": "#000000",
                 "text-halo-width": 1 
            },
            metadata: {
                'renderedOnServer': false
            }
        });
    

     mapView.on('click','polygons-layer-fill',(e)=> {
        let item = e.features[0]
        if(!props.showFooter){
          landInfo.value = {
            ...item.properties,
             longitude:e.lngLat.lng,
             latitude:e.lngLat.lat
          }
          showPop.value = true
          changePostion()
          return false

        }
          //如果包含原地块ID 移除地块
        if(selectLandList.value.includes(item?.id)){
          let index = selectLandList.value.indexOf(item?.id)
          selectLandList.value.splice(index, 1)
          mapView.setFeatureState({source: 'polygons-source', id: item?.id },{ click: false });
        }else{
            let landIds =[item.id]
            selectLandList.value=Array.from(new Set(selectLandList.value.concat(landIds)))
            mapView.setFeatureState({source: 'polygons-source', id: item?.id },{ click: true });
        }
      })

    //  mapView.on('mouseenter', 'polygons-layer-fill',(e)=> {
    //       mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'visible');
    // })
    
    //  mapView.on('mouseleave', 'polygons-layer-fill', (e)=> {
    //       mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'none');
    // })
}

const onChangeZoom =(row)=>{
if(row.currentZoom<15){
    mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'none');
}else{
    mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'visible');

}
changePostion()
}

const changePostion = () => {
  let item = landInfo.value 
   const point = refLandMap.value.getWindXY(Number(item.longitude||item.locationLongitude),Number(item.latitude||item.locationLatitude))
    const popOption = {
              title:item.farmLandNo,
              farmId:item.farmId,
              companyId:item.companyId,
              farmLandId:item.farmLandId,
              pic:item.pic,
              screenX: point.left,
              screenY: point.top+50,
              visible:true,
              btnText:'地块详情',
              footer:false,
              values: [
                  {
                      label: '地块名称',
                      value: item.farmLandName
                  },
                  {
                      label: '地块面积',
                      value:  Number(item.mapAreaSize||0).toFixed(2)+'亩'
                  },
                  {
                      label: '地块类型',
                      value: item.landTypeName||'--'
                  },
                  {
                      label: '作物类型',
                      value: (item.cropName||'--')+','+(item.cropSeriesName||'--')
                  }
              ],
              ...item
    }
    popObjct.value = popOption
}



const getSelectList=()=>{
  //获取地块分组列表
  getLandGroupList({farmId: userStore.userInfo.farmId}).then((res) => {
    if (res.success) {
      groupList.value = res.data || []
    }
  })
  //获取地块类型列表
  getLandTypeList({farmId: userStore.userInfo.farmId}).then((res) => {
    if (res.success) {
      landTypeList.value = res.data || []
    }
  })
}

const btnOpen = ()=>{
  showLeftView.value =!showLeftView.value
}

const changeFarmLandName =()=>{
    changeLandType(searchInfo.value)
}

const  changeLandType =(val)=>{
  checkedLand.value = false
  searchInfo.value = {...searchInfo.value,...val} 
  showPop.value = false
  updateData()
}

const changeCheckBox =(val)=>{
  let tableList = tableData.value
       if(searchInfo.value?.landGroupId){
        tableList= tableData.value.filter((item)=>{
          return item.landGroupId ==searchInfo.value?.landGroupId
        })
       }
       if(searchInfo.value?.landTypeId){
          tableList= tableData.value.filter((item)=>{
            return item.landTypeId ==searchInfo.value?.landTypeId
          })
       }
       if(searchInfo.value?.landTagId){
          tableList= tableData.value.filter((item)=>{
            return item.tagsId?.indexOf(searchInfo.value?.landTagId)>=0
          })
       }
       if(searchInfo.value?.farmLandName){
          tableList= tableData.value.filter((item)=>{
            return item.farmLandName?.indexOf(searchInfo.value?.farmLandName)>=0
          })
       }
  if(val){
      selectLandList.value=selectLandList.value.concat(tableList.map((item)=>item.farmLandId))
      selectLandList.value.forEach((Id)=>{
        mapView.setFeatureState({source: 'polygons-source', id: Id },{ click: true });
     })
  }else{
    removeLandColor()
  }

}


const saveLand =()=>{
   emit('change', {selects: selectLandList.value, total: getMapSize.value})
   btnBack()
}

const getMapSize = computed(()=>{
  let totalSize=0
  getLandTable.value.forEach((item)=>{
      totalSize+=(item?.mapAreaSize||0)
  })
  return totalSize.toFixed(1)
})

//删除所有地块
const btnAllDel =()=>{
  removeLandColor()
}
const removeLandColor =()=>{
  selectLandList.value.forEach((Id)=>{
         mapView.setFeatureState({source: 'polygons-source', id: Id },{ click: false });
      })
     window.setTimeout(() => {
        selectLandList.value=[]
    }, 200);
}

// 表格行单击处理事件
const setMapData = (row)=>{
   locationMap.value= {
      longitude:Number(row.locationLongitude),
      latitude:Number(row.locationLatitude)
  }
    let item= row
    if(!item){return}
    landInfo.value =item
    // changePostion()
    // showPop.value = true
}
const delCell=({farmLandId})=>{
  let index = selectLandList.value.findIndex(item => item ==farmLandId);
  selectLandList.value.splice(index,1)
  mapView.setFeatureState({source: 'polygons-source', id: farmLandId },{ click: false });
}
const btnBack = ()=>{
  emit('close')
}

const mapLocation = ()=>{

}
defineExpose({mapLocation})

</script>
<style>
.filter-view .el-select .el-input__inner{
  background-color: #f5f7fa;
} 

</style>
<style lang="scss" scoped>
.select-land-left-view{
      box-sizing: border-box;
      display: flex;
      flex-flow: column;
      height: 100%;
      padding: 0 10px 0 0;
      //overflow: hidden;
      .mass-view{
          display: flex;
          justify-content: space-between;
          padding: 6px 10px;
          border-bottom: 1px solid #ddd;
          margin-bottom: 10px;
          .name{
              font-size:15px;
              font-weight: bold;
              color: #333;
              position: relative;
              &::after{
                  position: absolute;
                  contain: '';
                  content:'';
                  height:16px;
                  width:2px;
                  background-color: #04AE70;
                  left: -5px;
              }
          }
      }
    .filter-view{
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f5f7fa;
        padding:6px 0;
        .el-input__inner{
          background-color: #f5f7fa;
        }
    }
}


.right-view-map{
  position: absolute;
  width:100%;
  height: calc(100vh - 95px);
  .tips-view-tools{
    position: absolute;
    top:10px;
    border:1px;
    height:40px;
    width:480px;
    z-index:99;
    left:50%;
    margin-left:-240px;
    display: flex;
  }
  .groug-change-view{
      position: absolute;
      bottom:15px;
      left:10px;
      z-index:99; 
      border:1px solid #a9a8a8;
      .groug-list{
          background-color: #00000080;
          .item{
              height:36px;
              line-height:36px;
              padding:0 10px;
              font-size:13px;
              color: #fff;
              position: relative;
              text-indent: 25px;
          }::after{
             position: absolute;
             height:10px;
             width:20px;
             border:1px solid #04AE70;
             content: '';
             left:5px;
             top:50%;
             margin-top:-5px;
             
          }.on::after{
              background-color:#04AE70;
          }.not::after{
              background-color:#888888;
              border:1px solid #888888;
          }
      }
  }
  .groug-right-view{
      position: absolute;
      bottom:15px;
      right:10px;
      z-index:99; 
      border:1px solid #a9a8a8;
      background-color: #00000080;
      padding:12px 20px;
      font-size:15px;
      color: #fff;
      text-align: center;
      .choose-land{
          margin: 8px 0px;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
      }
  }
 .groug-view{
      position: absolute;
      bottom:10px;
      left:10px;
      z-index:99;
      .groug-list{
          background-color: #fff;
          display: flex;
          justify-content: flex-start;
          .item{
              height:36px;
              line-height:36px;
              padding:0 12px;
              font-size:14px;
              cursor: pointer;
          }.on{
              background-color: #04AE70;
              color:#fff;
          }
      }
 }
}

</style>
